package contracts;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.log4j.Logger;
import util.JsonHelper;
import util.ReflectHelper;

import java.util.concurrent.ConcurrentHashMap;



/**
 * 契约类型序列化器
 * <p>
 * 内部存储类型名和类型的字典
 *
 * @author wyl
 */
public class ContractTypeSerializer {
    private static final Logger logger = Logger.getLogger(ContractTypeSerializer.class);
    private static final ConcurrentHashMap<String, Class<?>> types = new ConcurrentHashMap<>();

    static {
        String responsePackageName = "contracts.responses";
        String requestPackageName = "contracts.requests";
        ReflectHelper.findClassByAnnotated(responsePackageName, Response.class)
                .forEach(t -> {
                    types.put(t.getSimpleName(), t);
                });
        ReflectHelper.findClassByAnnotated(requestPackageName, Request.class)
                .forEach(t -> {
                    types.put(t.getSimpleName(), t);
                });
        //添加字符串
        types.put(String.class.getSimpleName(), String.class);
    }

    public static Object deserialize(String typeName, String json) {
        try {
            Class<?> type = types.get(typeName);
            if (type != null) {
                return JsonHelper.jsonToObject(json, type);
            } else {
                logger.fatal("没有找到类型名为" + typeName + "的类型");
            }
        } catch (JsonProcessingException e) {
            logger.error("为类型" + typeName + "反序列化失败");
            e.printStackTrace();
        }
        return null;
    }
}
